package com.shibo.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.shibo.order.entity.Order;
import com.shibo.order.service.OrderService;
import com.shibo.order.yml.OrderYml;
import lombok.extern.slf4j.Slf4j;
import org.apache.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

//@RequestMapping("/api/order")
@Slf4j
//@RefreshScope // 激活配置文件动态刷新
@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

//    @Value("${order.timeout}")
//    String orderTimeout;
//
//    @Value("${order.auto-confirm}")
//    String orderAutoConfirm;

    @Autowired
    OrderYml orderYml;

    @GetMapping("/config")
    public String config(){
        return "timeout:"+orderYml.getTimeout()+
                "，auto-confirm:"+orderYml.getAutoConfirm() +
                "，dbUrl:"+orderYml.getDbUrl();
    }

//    @GetMapping("/config")
//    public String config(){
//        return "timeout:"+orderTimeout+" auto-confirm:"+orderAutoConfirm;
//    }

    /**
     * 创建订单
     */
    @GlobalTransactional  //分布式注解
    @GetMapping("/create")
    public Order createOrder(@RequestParam("userId") Long userId,
                            @RequestParam("productId") Long productId) {

        Order order = orderService.createOrder(productId, userId);

        return order;
    }

    /**
     * 创建订单（秒杀）
     */
    @GetMapping("/createSeckill")
    @SentinelResource(value = "createSeckill",fallback = "createSeckillFallBack")
    public Order createSeckill(@RequestParam(value = "userId",required = false) Long userId,
                             @RequestParam(value = "productId",required = false) Long productId) {

        Order order = orderService.createOrder(productId, userId);

        order.setId(Long.MAX_VALUE);

        return order;
    }

    public Order createSeckillFallBack(Long userId, Long productId, Throwable exception){
        System.out.println("createSeckillFallBack。。。");
        Order order1 = new Order();
        order1.setId(productId);
        order1.setUserId(userId);
        order1.setAddress("异常信息：" + exception.getClass());
        return order1;
    }

    @GetMapping("/readDB")
    public String readDB(){
        log.info("readDB...");
        return "readDB success...";
    }

    @GetMapping("/writeDB")
    public String writeDB(){
        log.info("writeDB...");
        return "writeDB success...";
    }

}
